import pickle
import json

#读txt文件为python对象
#txt=load_txtfile(open_name)
def load_txtfile(open_name): #读
    f = open(open_name)
    txt =f.readlines()
    f.close()
    # print(txt)
    return txt

#写python对象为txt文件
def save_txtfile(data,open_name): #读
    f = open(open_name)
    f.write(data)
    # 注意关闭文件
    f.close()
    # print(txt)
    return

# 功能：加载读pickle文件为list对象
# items = loadpick(file_name)
# file_name='P1.pickle'
#pickle.load报错：_pickle.UnpicklingError: invalid load key, '\xef'.
#pickle中存储的数据类型应该是：list, tuple, or dict
def loadpick(filename):
    data = []
    with open(filename, "rb") as f:
        while True:
            try:
                data.append(pickle.load(f))
            except EOFError:
                break
    return data
    # with open(filename, "rb") as f:
    #     while True:
    #         try:
    #             yield pickle.load(f)#yield返回一个生成器generator#可通过next(generator)调用
    #         except EOFError:
    #             break


#写python对象为pickle
def save2pickfile(file_name,data):
	pickle.dump(data,open(file_name,"wb"))#pickle.dump(list(data),open(file_name,"wb"))

"""功能：数据类型判断-是否为指定类型；
data:对象；
sup=[list,tuple, dict]；指定的数据类型"""
def judge_tpye(data,sup):
    if type(data) in sup:  # type() 不会认为子类是一种父类类型，不考虑继承关系#isinstance() 会认为子类是一种父类类型，考虑继承关系
        return True
    else:
        print("error不在支持的数据类型是：",sup)
        return False

# pickle文件-转换写入txt文件
open_name='P1.txt'
save_name='P1.pickle'
# txt2pick(open_name,save_name)
def txt2pick(open_name,save_name):
    f = open(open_name)
    data = f.readlines()
    # data=f.read().splitlines()#去除换行符-按照行(’\r’, ‘\r\n’, \n’)分隔，返回一个包含各行作为元素的列表
    sup=[list,tuple, dict]
    if judge_tpye(list(data),sup):
        file = open(save_name, 'wb')
        # data = str(txt)  # 转换变量为str格式；TypeError: write() argument must be str, not list
        pickle.dump(data,file)
        # 注意关闭文件
        file.close()
        f.close()
        print(open_name,"成功写入到",save_name,"--写入数据类型为：",type(data))
    # else:
    #     print("pickle中存储的数据类型应该是：list, tuple, or dict")
    return
txt2pick(open_name,save_name)

# pickle文件-转换写入txt文件
open_name='P1.pickle'
save_name='p1.txt'
# pick2txt(open_name,save_name)
# _pickle.UnpicklingError: invalid load key, '\xc8'.
def pick2txt(open_name,save_name):
    # # with open(open_name, 'rb') as pf:
    # #     fi = pickle.load(pf)
    # fi = open(open_name, 'rb+')
    # data = pickle.load(fi)#_pickle.UnpicklingError: invalid load key, '\xef'.不是编码问题
    # txt_file = open(save_name, 'w')
    # # fi = str(data)  # 转换变量为str格式；TypeError: write() argument must be str, not list
    # data=load_pickfile(open_name)
    data = loadpick(open_name)#print(type(data))#<class 'generator'>
    print(data)
    # save_txtfile(data,save_name)
pick2txt(open_name,str(save_name))


# print(info)
'''dict对象类型-写入txt文件
# 先创建并打开一个文本文件
file = open('dict.txt', 'w')
# 遍历字典的元素，将每项元素的key和value分拆组成字符串，注意添加分隔符和换行符
for k, v in pf.items():
    file.write(str(k) + ' ' + str(v) + '\n')
'''

# 字典输出的项是无序的，如果想按照字典的key排序输出的话，可以按照下面的方式实现
# for k,v in sorted(dict_temp.items()):
# 	file.write(str(k)+' '+str(v)+'\n')
# file.close()

'''str写入txt文件
with open('file.txt','w') as f_ob:
    f_ob.write(info)
'''

#保存info变量内容到f_ob文件对象
'''
with open('file.json','w') as f_ob:
    json.dump(info,f_ob)
'''
